package cn.bnjy.common;

import cn.bnjy.util.HttpUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

/**
 * 描述：
 *
 * @date: 2018/11/3 14:27
 * @author: chavin
 */
@Slf4j
public class WeiXinAccessToken {

    private static String ACCESS_TOKEN = "";

    private WeiXinAccessToken() {

    }

    /**
     * 获取AccessToken
     * @return
     */
    public static String getToken() {
        if (StringUtils.isBlank(ACCESS_TOKEN)) {
            synchronized (ACCESS_TOKEN) {
                if (StringUtils.isBlank(ACCESS_TOKEN)) {
                    log.info("token 为空，重新获取token");
                    getTokenFromWeiXin();
                }
            }
        }
        return ACCESS_TOKEN;
    }

    // 从微信获取access_token {"access_token":"ACCESS_TOKEN","expires_in":7200}
    public static void getTokenFromWeiXin() {
        String result = HttpUtils.get(WeiXinApi.ACCESS_TOKEN.replace("APPID", EasyData.CONFIG_MAP.get(WeiXinConstant.APPID)).replace("APPSECRET", EasyData.CONFIG_MAP.get(WeiXinConstant.APPSECRET)));
        if(StringUtils.isNotBlank(result)) {
            JSONObject obj = JSON.parseObject(result);
            ACCESS_TOKEN = obj.getString("access_token");
            log.info("自动获取access_token：{}", ACCESS_TOKEN);
        } else {
            ACCESS_TOKEN = "";
            log.error("自动获取access_token失败");
        }
    }

}
